package com.grapecity.circlefriend.activity;

import com.grapecity.circlefriend.CircleApplication;
import com.grapecity.circlefriend.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;

public class SplashActivity extends Activity {

	private CircleApplication app;

	private static final int SHOW_TIME_MIN = 2000;
	private long startTime;

	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case CircleApplication.INIT_OK:
				long loadingTime = System.currentTimeMillis() - startTime;
				if (loadingTime < SHOW_TIME_MIN) {
					handler.postDelayed(goToMainActivity, SHOW_TIME_MIN - loadingTime);
				} else {
					handler.post(goToMainActivity);
				}
				break;
			default:
				break;
			}
		}
	};

	Runnable goToMainActivity = new Runnable() {
		@Override
		public void run() {
			SplashActivity.this.startActivity(new Intent(SplashActivity.this, MainActivity.class));
			finish();
			overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash);

		startTime = System.currentTimeMillis();
		app = (CircleApplication) getApplication();

		new AsyncTask<Void, Void, Integer>() {
			@Override
			protected Integer doInBackground(Void... params) {
				app.initApplication(handler);
				return 0;
			}
		}.execute(new Void[] {});
	}
}
